import os, json

from django.core.exceptions import ImproperlyConfigured


def get_env_variable(var_name):
    """
    从OS中获取配置参数
    :param var_name:
    :return: 环境变量或者异常

    SOME_SECRET_KEY = get_env_variable('SOME_SECRET_KEY')
    """
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = f'Set the {var_name} environment variable'
        raise ImproperlyConfigured(error_msg)


# JSON-based secrets module
with open('secrets.json') as f:
    secrets = json.loads(f.read())


def get_secret(setting, secrets=secrets):
    """
    从文件中获取配置参数
    :param setting:
    :param secrets:
    :return:
    """
    try:
        return secrets[setting]
    except KeyError:
        error_msg = f'Set the {setting} environment variable'
        raise ImproperlyConfigured(error_msg)


SECRET_KEY = get_secret('SECRET_KEY')
